#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
导入完整的1260条民法典数据到MongoDB
"""

import json
import os
from datetime import datetime
from pymongo import MongoClient
from typing import List, Dict, Any

def import_complete_data():
    """导入完整数据到MongoDB"""
    print("📥 开始导入完整的民法典数据到MongoDB...")
    
    try:
        # 连接MongoDB
        client = MongoClient("mongodb://localhost:27017/")
        db = client['civil_code_db']
        collection = db['civil_code_articles']
        
        # 加载完整数据
        data_file = "data/civil_code_complete_1260.json"
        if not os.path.exists(data_file):
            print("❌ 未找到完整数据文件")
            return False
        
        with open(data_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        articles = data.get('articles', [])
        print(f"📄 加载数据: {len(articles)} 条法条")
        
        # 清空现有数据
        print("🗑️ 清空现有数据...")
        collection.delete_many({})
        
        # 处理数据：移除_id字段
        for article in articles:
            if '_id' in article:
                del article['_id']
        
        # 批量插入数据
        print("📥 批量插入数据...")
        result = collection.insert_many(articles)
        
        print(f"✅ 成功导入 {len(result.inserted_ids)} 条法条")
        
        # 验证数据
        total_count = collection.count_documents({})
        print(f"📊 数据库中总计: {total_count} 条法条")
        
        # 按编统计
        print(f"\n📚 按编统计:")
        pipeline = [
            {"$group": {
                "_id": "$chapter_info.part",
                "count": {"$sum": 1}
            }},
            {"$sort": {"_id": 1}}
        ]
        
        part_stats = list(collection.aggregate(pipeline))
        for stat in part_stats:
            part_name = stat['_id'] or "未分类"
            print(f"   - {part_name}: {stat['count']} 条")
        
        client.close()
        return True
        
    except Exception as e:
        print(f"❌ 数据导入失败: {str(e)}")
        return False

def main():
    """主函数"""
    print("=" * 60)
    print("📥 导入完整民法典数据到MongoDB")
    print("=" * 60)
    
    if import_complete_data():
        print("\n🎉 数据导入成功！")
    else:
        print("\n❌ 数据导入失败")

if __name__ == "__main__":
    main()
